package com.zhongyewx.teachercert.base;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.classic.common.MultipleStatusView;
import com.umeng.analytics.MobclickAgent;
import com.zhongyewx.teachercert.ZYApplication;
import com.zhongyewx.teachercert.utils.ZYToastUtil;
import com.zhongyewx.teachercert.views.ZYPtrClassicListHeader;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public abstract class ZYBaseFragment extends Fragment implements EasyPermissions.PermissionCallbacks {

    /**
     * 视图是否加载完毕
     */
    private boolean isViewPrepare = false;

    /**
     * 数据是否加载过了
     */
    private boolean hasLoadData = false;

    /**
     * 多种状态的 View 的切换
     */
    private MultipleStatusView mLayoutStatusView = null;

    protected PtrFrameLayout ptrFrameLayout = null;
    private FragmentActivity mContext;
    protected View mRootView;

    Unbinder unbinder;

    private Handler mHandler = new Handler();
    Runnable postDelayed = new Runnable() {
        @Override
        public void run() {
            if (!isAdded()) {
                return;
            }
            ZYToastUtil.showCenterToast(getActivity(), "刷新失败请重试");
            if (ptrFrameLayout != null && ptrFrameLayout.isRefreshing()) {
                ptrFrameLayout.refreshComplete();
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(getLayoutId(), container, false);
        unbinder = ButterKnife.bind(this, mRootView);
        return mRootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser)
            lazyLoadDataIfPrepared();
        if (!isVisibleToUser) {
            if (ptrFrameLayout != null && ptrFrameLayout.isRefreshing()) {
                ptrFrameLayout.refreshComplete();
            }
        }

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewPrepare = true;
        mContext = getActivity();
        initView();
        lazyLoadDataIfPrepared();
        initData();
        if (mLayoutStatusView != null)
            mLayoutStatusView.setOnRetryClickListener(mRetryClickListener);
        if (ptrFrameLayout != null){
            initPtr();
        }

    }

    /**
     * 初始化(配置)下拉刷新组件
     */
    private void initPtr() {
        float scale = getResources().getDisplayMetrics().density;
        ZYPtrClassicListHeader header = new ZYPtrClassicListHeader(mContext);
        header.setLastUpdateTimeRelateObject(this);
        header.setPadding(0, (int) (15 * scale + 0.5f), 0, (int) (15 * scale + 0.5f));
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.addPtrUIHandler(header);
        ptrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                lazyLoad();
                if (mHandler != null && postDelayed != null)
                    mHandler.postDelayed(postDelayed, 5000);
            }
        });
    }

    View.OnClickListener mRetryClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            lazyLoad();
        }
    };

    /**
     *  加载布局
     */
    public abstract @LayoutRes
    int getLayoutId();

    /**
     * 初始化 View
     */
    public abstract void initView();

    /**
     * 初始化数据
     */
    public  abstract void initData();


    public abstract void lazyLoad();

    private void lazyLoadDataIfPrepared(){
        if (getUserVisibleHint() && isViewPrepare && !hasLoadData) {
            lazyLoad();
            hasLoadData = true;
        }
    }


    public void PermissionsGranted(int requestCode){};


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName()); //统计页面("MainScreen"为页面名称，可自定义)
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageStart(this.getClass().getSimpleName()); //统计页面("MainScreen"为页面名称，可自定义)
    }

    @Override
    public void onStop() {
        if (ptrFrameLayout != null && ptrFrameLayout.isRefreshing()) {
            ptrFrameLayout.refreshComplete();
        }
        if (mHandler != null) {
            mHandler.removeCallbacks(postDelayed);
            mHandler = null;
            postDelayed = null;
        }
        super.onStop();
    }

    @Override
    public void onDestroy() {
        if (getActivity() != null) {
            ZYApplication.getRefWatcher().watch(getActivity());
        }
        super.onDestroy();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * 重写要申请权限的Activity或者Fragment的onRequestPermissionsResult()方法，
     * 在里面调用EasyPermissions.onRequestPermissionsResult()，实现回调。
     *
     * @param requestCode  权限请求的识别码
     * @param permissions  申请的权限
     * @param grantResults 授权结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 当权限被成功申请的时候执行回调
     *
     * @param requestCode 权限请求的识别码
     * @param perms       申请的权限的名字
     */
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        PermissionsGranted(requestCode);
        Log.i("EasyPermissions", "获取成功的权限$perms");
    }

    /**
     * 当权限申请失败的时候执行的回调
     *
     * @param requestCode 权限请求的识别码
     * @param perms       申请的权限的名字
     */
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        StringBuffer sb = new StringBuffer();
        for (String str : perms) {
            sb.append(str);
            sb.append("\n");
        }
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this)
                    .setRationale("此功能需要" + sb + "权限，否则无法正常使用，是否打开设置")
                    .setPositiveButton("好")
                    .setNegativeButton("不行")
                    .build()
                    .show();
        }
    }
}
